<?php
namespace app\index\controller;
use think\Controller;

class Index extends Controller
{
    public $obj;
    public function index()
    {
        $this->log($_GET);

        if(isset($_GET['echostr'])){
            if($this->checkSing()){
                echo $_GET['echostr'];
            }
        }else{

            // if(!$this->checkSing()){
            //     return false;
            // }

            $this->request();
        }
    }

    public function  request()
    {
        $data = $GLOBALS['HTTP_RAW_POST_DATA'];

        $this->obj = simplexml_load_string($data, 'SimpleXMLElement', LIBXML_NOCDATA);





        switch ($this->obj->MsgType) {
            case 'text':
                $this->responText();
                break;
            case 'image':
                $this->responImage();
                break;
            default:
                # code...
                break;
        }


        
    }

    public function responImage()
    {
        // $data = $xbs+200;

       $str = "<xml>
        <ToUserName><![CDATA[".$this->obj->FromUserName."]]></ToUserName>
        <FromUserName><![CDATA[".$this->obj->ToUserName."]]></FromUserName>
        <CreateTime>".time()."</CreateTime>
        <MsgType><![CDATA[image]]></MsgType>
        <Image><MediaId><![CDATA[".$this->obj->MediaId."]]></MediaId></Image>
        </xml>";

        echo $str;

        // $str = "<xml>
        // <ToUserName><![CDATA[".$this->obj->FromUserName."]]></ToUserName>
        // <FromUserName><![CDATA[".$this->obj->ToUserName."]]></FromUserName>
        // <CreateTime>".time()."</CreateTime>
        // <MsgType><![CDATA[image]]></MsgType>
        // <Image>
        // <MediaId><![CDATA[".$this->obj->MediaId."]]></MediaId>
        // </Image>
        // </xml>";
        // echo $str;
    }

    public function responText()
    {

        $str = "<xml>
        <ToUserName><![CDATA[".$this->obj->FromUserName."]]></ToUserName>
        <FromUserName><![CDATA[".$this->obj->ToUserName."]]></FromUserName>
        <CreateTime>".time()."</CreateTime>
        <MsgType><![CDATA[text]]></MsgType>
        <Content><![CDATA["."你也好"."]]></Content>
        </xml>";

        echo $str;

    }

    public function log($data)
    {
        $data['data'] = json_encode($data);
        $data['ctime'] = time();
        db('log')->insert($data);
    }

     public function logshow()
    {
        
        $data = db('log')->order('ctime desc')->select();

        var_dump($data);
    }



    public function checkSing()
    {
       $signature = $_GET['signature'];

       $timestamp = $_GET['timestamp'];

       $nonce = $_GET['nonce'];

       $token = "xbs2017";

       $tmpArr = array( $token,$timestamp, $nonce);

       sort($tmpArr, SORT_STRING);

       $tmpStr = implode( $tmpArr );

       $sign = sha1( $tmpStr );

       if( $signature ==$sign ){
            return true;
       }else{
            return false;
       }
    }
   
}
